//
//  ByUIWithdrawNewVC.m
//  chequanbao_ios
//
//  Created by mc on 2017/7/7.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIWithdrawNewVC.h"

// api
#import "ByApiMine.h"

// cell
#import "ByCellWithdraw.h"
#import "ByCellWithdrawInfo.h"

// other
#import "ZKCityPickerView.h"

@interface ByUIWithdrawNewVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,ZKCityPickerViewDelegate>
// view
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) ZKCityPickerView *cityView;
@property (nonatomic, strong) UILabel *arealabel;

// data
@property (nonatomic, strong) NSArray *bankAry;             // 银行数组
@property (nonatomic, strong) NSMutableArray *selectArray;

@property (nonatomic, strong) NSArray *titleAry;

@property (nonatomic, copy)   NSString *minePoints;

@property (nonatomic, strong) NSMutableArray *infoAry;      // 用来存放信息数组


@property (nonatomic, copy) NSString *areaStr;

@end

@implementation ByUIWithdrawNewVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"收入提现";
    [self.selectArray addObject:@YES];
    [self.selectArray addObject:@NO];
    [self.selectArray addObject:@NO];
    [self.selectArray addObject:@NO];
    [self.selectArray addObject:@NO];
    
    [self addLeftBackBarButtonItem];
    
    [self fetchMinePoints];

}

#pragma mark -- getter
-(NSArray *)bankAry{
    if (!_bankAry) {
        _bankAry = @[@"mine_gongshang",@"mine_zhongguo",@"mine_jiaotong",@"mine_nongye",@"mine_jianshe"];
    }
    return _bankAry;
}

- (NSMutableArray *)selectArray {
    
    if (!_selectArray) {
        _selectArray = [[NSMutableArray alloc] init];
    }
    return _selectArray;
}

-(NSArray *)titleAry{
    if (!_titleAry) {
        _titleAry = @[@"姓名",@"联系方式",@"提现金额",@"卡号",@"选择省市区",@"收款账户开户网点"];
    }
    return _titleAry;
}

-(ZKCityPickerView *)cityView{
    if (!_cityView) {
        _cityView = [[ZKCityPickerView alloc] initWithPicker];
        _cityView.delegate = self;
        [self.view addSubview:_cityView];
    }
    return _cityView;
}

-(NSMutableArray *)infoAry{
    if (!_infoAry) {
        NSArray *temp = @[@"",@"",@"",@"",@"",@""];
        _infoAry = [temp mutableCopy];
    }
    return _infoAry;
}

#pragma mark -- 获取数据
// 获取车险金
- (void)fetchMinePoints{
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.uid = BY_USER.uid;
    model.code_type = BY_USER.account_id;
    [self performSelector:@selector(afterLoad:) withObject:@"加载中..." afterDelay:0.01];
    [ByApiMine getMinePoints:model success:^(ByNetBaseResult *result) {
        ByModelUser *user = [ByCacheUser getUserInfo];
        user.points = [result.data objectForKey:@"score1"];
        [ByCacheUser setUserInfo:user];
        self.minePoints = [NSString stringWithFormat:@"我的收入：%.2f元",[user.points floatValue]/100.0];
        [self initTable];
        [ByCoreToolAlert hideHud];
        
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    
}
- (void)afterLoad:(NSString *) str{
    [ByCoreToolAlert showLoadind:str];
}

#pragma mark -- 创建视图
- (void)initTable{
    [self createHeaderView];
    // table
    _table = [[UITableView alloc] initWithFrame:CGRectMake(0, _headerView.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - _headerView.bottom - 40)];
    [self.view addSubview:_table];
    _table.separatorStyle = UITableViewCellSeparatorStyleNone;
    _table.backgroundColor = [UIColor clearColor];
    _table.delegate = self;
    _table.dataSource = self;
    if (@available(iOS 11.0,*)) {
        NSLog(@"%lf----%lf----%lf",self.view.height,self.view.safeAreaInsets.top,self.view.safeAreaInsets.bottom);
        _table.height = self.view.height - self.view.safeAreaInsets.top - self.view.safeAreaInsets.bottom - 50 - 40;
    }else{
        _table.height = SCREEN_HEIGHT - _headerView.bottom - 40;
    }
    
    [self createBottomView];
    
}

// 创建headerview
- (void)createHeaderView{
    // header
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(10, 64, SCREEN_WIDTH - 20, 50)];
    _headerView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.25];
    _headerView.layer.cornerRadius = 50/2.0;
    
    // 积分
    CGFloat x,y,width,height;
    width = [self.minePoints getSizeOfString:16].width;
    height = 20;
    x = (SCREEN_WIDTH - 20 - width)/2.0 + 25;
    y = 15;
    UILabel *pointLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    pointLabel.text = self.minePoints;
    pointLabel.font = FONT(16);
    pointLabel.textColor = [UIColor whiteColor];
    [_headerView addSubview:pointLabel];
    
    // 图标
    x = CGRectGetMinX(pointLabel.frame) - 25;
    y = y ;
    width = height = 20;
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    img.image = [UIImage imageNamed:@"mine_small_points"];
    [_headerView addSubview:img];
    
    [self.view addSubview:_headerView];
    
    if (@available(iOS 11.0,*)) {
        _headerView.top = self.view.safeAreaInsets.top;
    }else{
        _headerView.top = 64;
    }
    
}

// 创建底部button
- (void)createBottomView{
    UIButton *withdrawBtn = [[UIButton alloc] initWithFrame:
                             CGRectMake(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40)];
    withdrawBtn.backgroundColor = BY_THEME_COLOR;
    [withdrawBtn setTitle:@"提现" forState:UIControlStateNormal];
    [self.view addSubview:withdrawBtn];
    if (@available(iOS 11.0,*)) {
        withdrawBtn.bottom = self.view.height - self.view.safeAreaInsets.bottom;
    }else{
        withdrawBtn.bottom = self.view.height;
    }
    [withdrawBtn addTarget:self action:@selector(withdraw:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource
// 返回信息组 + 银行组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titleAry.count + 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section < self.titleAry.count) {
        return 1;
    }
    return self.bankAry.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section < self.titleAry.count) {
        static NSString *indentier = @"customCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentier];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subview in cell.subviews) {
            [subview removeFromSuperview];
        }
        
        CGFloat x,y,width,height;
        x = 10;
        y = 0;
        height = 50;
        width = SCREEN_WIDTH - 20;
        UIView *bgview = [[UIView alloc] initWithFrame:CGRectMake(x, y, width,height )];
        bgview.backgroundColor = [UIColor colorWithWhite:0.95 alpha:0.25];
        bgview.layer.cornerRadius = 4.0;
        [cell addSubview:bgview];
        
        // 标题
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 10, [@"收款账户开户网点" getSizeOfString:14].width, 30)];
        titleLabel.font = FONT(14);
        titleLabel.textColor = [UIColor colorWithWhite:0.90 alpha:1];
        titleLabel.text = self.titleAry[indexPath.section];
        [cell addSubview:titleLabel];
        
        if (indexPath.section != 4) {
            // 输入框
            UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(titleLabel.right + 20, 10, SCREEN_WIDTH - titleLabel.right - 20 - 20, 30)];
            tf.tag = 10 + indexPath.section;
            tf.textColor = [UIColor whiteColor];
            tf.delegate = self;
            tf.font = FONT(14);
            [cell addSubview:tf];
            if (self.infoAry.count != 0) {
                tf.text = self.infoAry[indexPath.section];
            }
            
            if (indexPath.section == 2) {
                tf.keyboardType = UIKeyboardTypeDecimalPad;
            }
        }
        else{
            // 输入框
            _arealabel = [[UILabel alloc] initWithFrame:CGRectMake(titleLabel.right + 20, 10, SCREEN_WIDTH - titleLabel.right - 20 - 20, 30)];
            _arealabel.tag = 10 + indexPath.section;
            _arealabel.textColor = [UIColor whiteColor];
            _arealabel.text = self.infoAry[indexPath.section];
            _arealabel.font = FONT(14);
            [cell addSubview:_arealabel];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectArea)];
            _arealabel.userInteractionEnabled = YES;
            [_arealabel addGestureRecognizer:tap];
        
        }
        return cell;
    }else{
        ByCellWithdraw *cell = [ByCellWithdraw cellWithTableView:tableView];
        cell.imgStr = self.bankAry[indexPath.row];
        cell.select = [self.selectArray[indexPath.row] boolValue];
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == self.titleAry.count) {
        for (int i = 0; i < self.selectArray.count; i ++) {
            if (i == indexPath.row) {
                [self.selectArray replaceObjectAtIndex:i withObject:@YES];
            } else {
                [self.selectArray replaceObjectAtIndex:i withObject:@NO];
            }
        }
        [self.table reloadData];
    }
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section < self.titleAry.count) {
        return 50;
    }
    return 53;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

#pragma mark -- textfieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self.infoAry replaceObjectAtIndex:textField.tag - 10 withObject:textField.text];
    [self.table reloadData];

}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [self.cityView close];
}

// 地区选择
- (void)selectArea{
    UITableViewCell *cell = [_table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UITextField *nameTf = [cell viewWithTag:10];
    [nameTf resignFirstResponder];
    
    cell = [_table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    UITextField *phoneTf = [cell viewWithTag:11];
    [phoneTf resignFirstResponder];
    
    cell = [_table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    UITextField *priceTf = [cell viewWithTag:12];
    [priceTf resignFirstResponder];
    
    cell = [_table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:3]];
    UITextField *cardTf = [cell viewWithTag:13];
    [cardTf resignFirstResponder];
    
    cell = [_table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:5]];
    UITextField *wangTf = [cell viewWithTag:15];
    [wangTf resignFirstResponder];

    
    [self.cityView open];
}

- (void)cityPickerViewDidChooseAddress:(CityObject *)cityModel{
    NSLog(@"%@---%@---%@",cityModel.province,cityModel.city,cityModel.area);
    if ([cityModel.city isEqualToString:@"市辖区"] || [cityModel.city isEqualToString:@"县"]) {
        self.areaStr = [NSString stringWithFormat:@"%@%@",cityModel.province,cityModel.area];
    }else if([cityModel.area isEqualToString:@"市辖区"]){
        self.areaStr = [NSString stringWithFormat:@"%@%@",cityModel.province,cityModel.city];
    }else{
        self.areaStr = [NSString stringWithFormat:@"%@%@%@",cityModel.province,cityModel.city,cityModel.area];
    }
//    self.arealabel.text = self.areaStr;
    [self.infoAry replaceObjectAtIndex:4 withObject:self.areaStr];
    [self.table reloadData];
}
#pragma mark --
- (void)withdraw:(UIButton *)btn{

    
    for (NSString *str in self.infoAry) {
        if ([str isEqualToString:@""]) {
            [ByCoreToolAlert showOnlyText:@"请填写完整信息"];
            return;
        }
    }
//    if ([self.infoAry[2] integerValue] < 100) {
//        [ByCoreToolAlert showOnlyText:@"提现金额至少为100"];
//        return;
//    }
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.bank_card_name = [self.areaStr stringByAppendingString:@","];
    model.bank_card_name = [model.bank_card_name stringByAppendingString:self.infoAry[5]];
    model.bank_card_name = [model.bank_card_name stringByAppendingString:@","];
    NSInteger index = [self.selectArray indexOfObject:@YES];
    switch (index) {
        case 0:
            model.bank_card_name = [model.bank_card_name stringByAppendingString:@"中国工商银行"];
            break;
        case 1:
            model.bank_card_name = [model.bank_card_name stringByAppendingString:@"中国银行"];
            break;
        case 2:
            model.bank_card_name = [model.bank_card_name stringByAppendingString: @"交通银行"];
            break;
        case 3:
            model.bank_card_name = [model.bank_card_name stringByAppendingString:@"中国农业银行"];
            break;
        case 4:
            model.bank_card_name = [model.bank_card_name stringByAppendingString:@"中国建设银行"];
            break;
            
        default:
            break;
    }
    
    model.role_type = BY_USER.account_id;
    model.account_id = BY_USER.uid;
    model.score = [NSString stringWithFormat:@"%.2f",[self.infoAry[2] floatValue] * 100];
    model.bank_card_no = self.infoAry[3];
    model.name = self.infoAry[0];
    model.mobile = self.infoAry[1];
    [self performSelector:@selector(afterLoad) withObject:nil afterDelay:0.01];
    [ByApiMine applyforcash:model success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showOnlyText:result.data];
        [self performSelector:@selector(popVc) withObject:nil afterDelay:1];
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showOnlyText:result.msg];
    }];
    
    
}

- (void)afterLoad{
    [ByCoreToolAlert showLoadind:@"申请中..."];
}

- (void)popVc{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
